package com.sdx.console.spread.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.spread.entity.SpreadChannel;
import com.sdx.console.spread.service.SpreadChannelService;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @ClassName SpreadShareController
 * @Description 分享推广码
 * @Author kangbin
 * @Date 2020/3/20 15:59
 */
@RequestMapping("/spread/channel")
@Controller
public class SpreadChannelController extends AuthorizedBaesController {

    private static final String MODEL = "/spread/channel";

    @Resource
    private SpreadChannelService spreadChannelService;

    @Resource
    private ChannelSetService channelSetService;

    @Resource
    private CorePlatformService corePlatformService;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private OrgConsoleService orgConsoleService;

    /**
     * 初始化页面需要的列表数据，
     *
     */
    private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        Integer accessType = corePlatformService.getAccessType(request);
        List<ChannelSet> channelList = channelSetService.selectAuthChannels(accessType, user.getOrgId(),user.getTenantId());
        view.addObject("channels",channelList);
        view.addObject("accessType",accessType);

        if (accessType==6) {
            view.addObject("orgList", orgConsoleService.getOrgs());
        }
    }

    /* 页面 */

    @GetMapping("/index.do")
    @Function("spread.channel.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request,String channelCode) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        view.addObject("channel",channelCode);
        return view;
    }

    @PostMapping("/list.json")
    @Function("spread.channel.query")
    @ResponseBody
    public JsonResult<PageQuery> list(SpreadChannel condtion, HttpServletRequest request,String channel)
    {
        CoreUser user = getLoginUser(request);
        if(StringUtils.isNotEmpty(channel)){
            condtion.setChannelCode(channel);
        }
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        spreadChannelService.queryByCondition(page);
        return JsonResult.success(page);
    }


    @GetMapping("/edit.do")
    @Function("spread.channel.edit")
    @ResponseBody
    public ModelAndView edit(String promoteCode,HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        SpreadChannel spreadChannel = spreadChannelService.queryById(promoteCode);
        view.addObject("promoteRecord", spreadChannel);
        setPageParam(view,request);
        try {
            view.addObject("promoteRecordJson", JacksonUtils.toJsonString(spreadChannel,JacksonUtils.DF1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }

    @GetMapping("/add.do")
    @Function("spread.channel.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        return view;
    }

    private JsonResult save(boolean isNew,SpreadChannel promoteRecord,HttpServletRequest request
    ) {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        if (StringUtils.isEmpty(promoteRecord.getPromoteName())) {
            promoteRecord.setPromoteName(promoteRecord.getPromoteCode());
        }
        if (isNew) {
            String promoteCode = null;
            while(promoteCode==null) {
                promoteCode = Utils.getRandomStringByLength(10);
                //
                if (spreadChannelService.selectCodeCount(promoteCode)>0) {
                    promoteCode = null;
                }
            }
            Integer accessType = corePlatformService.getAccessType(request);
            if (accessType==null || 1==accessType) {
                //个人
                String customerId = customerInfoService.getCustomerId(user.getId().intValue());
                promoteRecord.setCustomerId(customerId);
                promoteRecord.setPromoterType("a");
            }
            if (accessType==null || 3==accessType || 1==accessType) {
                promoteRecord.setOrgId(user.getOrgId().intValue());
            }
            promoteRecord.setTenantId(user.getTenantId());
            promoteRecord.setPromoteCode(promoteCode);
            promoteRecord.setCreatedBy(user.getId().intValue());
            promoteRecord.setCreatedName(user.getName());
            promoteRecord.setCreatedTime(new Date());
            spreadChannelService.save(promoteRecord);
        } else {
            promoteRecord.setUpdatedBy(user.getId().intValue());
            promoteRecord.setUpdatedName(user.getName());
            promoteRecord.setUpdatedTime(new Date());
            spreadChannelService.updateTemplate(promoteRecord);
        }
        return result;
    }
    @PostMapping("/add.json")
    @Function("spread.channel.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)SpreadChannel promoteRecord, HttpServletRequest request
    )
    {
        Integer accessType = corePlatformService.getAccessType(request);

        if (accessType.intValue()==3) {
            CoreUser user = getLoginUser(request);
            promoteRecord.setOrgId(user.getOrgId().intValue());
        }
        return save(true,promoteRecord,request
        );
    }

    @PostMapping("/update.json")
    @Function("spread.channel.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  SpreadChannel promoteRecord,HttpServletRequest request
    ) {
        return save(false,promoteRecord,request
        );
    }

    @PostMapping("/delete.json")
    @Function("spread.channel.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
        List<String> idList = new ArrayList<String>();
        Collections.addAll(idList,ids.split(","));
        spreadChannelService.batchDelPromoteRecord(idList);
        return JsonResult.success();
    }

}
